package com.ruoyi.web.TemuEvents.service.impl;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ruoyi.web.TemuEvents.domain.TemuEvents;
import com.ruoyi.web.TemuEvents.mapper.TemuEventsMapper;
import com.ruoyi.web.TemuEvents.service.ITemuEventsService;
import com.ruoyi.web.TemuSalesData.domain.TemuSalesData;
import com.ruoyi.web.TemuSalesData.mapper.TemuSalesDataMapper;
import com.ruoyi.web.TemuStore.domain.TemuStore;
import com.ruoyi.web.TemuStore.mapper.TemuStoreMapper;
import com.ruoyi.web.utils.Httpapi;
import com.ruoyi.web.utils.TemuApi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * TemuEventsService业务层处理
 * 
 * @author kzc
 * @date 2025-07-25
 */
@Service
public class TemuEventsServiceImpl implements ITemuEventsService
{
    @Autowired
    private TemuEventsMapper temuEventsMapper;

    @Autowired
    private TemuSalesDataMapper temuSalesDataMapper;
    @Autowired
    private TemuStoreMapper temuStoreMapper;
    /**
     * 查询TemuEvents
     * 
     * @param id TemuEvents主键
     * @return TemuEvents
     */
    @Override
    public TemuEvents selectTemuEventsById(Integer id)
    {
        return temuEventsMapper.selectTemuEventsById(id);
    }

    /**
     * 查询TemuEvents列表
     * 
     * @param temuEvents TemuEvents
     * @return TemuEvents
     */
    @Override
    public List<TemuEvents> selectTemuEventsList(TemuEvents temuEvents)
    {
        return temuEventsMapper.selectTemuEventsList(temuEvents);
    }

    /**
     * 新增TemuEvents
     * 
     * @param temuEvents TemuEvents
     * @return 结果
     */
    @Override
    public int insertTemuEvents(TemuEvents temuEvents)
    {
        return temuEventsMapper.insertTemuEvents(temuEvents);
    }

    /**
     * 修改TemuEvents
     * 
     * @param temuEvents TemuEvents
     * @return 结果
     */
    @Override
    public int updateTemuEvents(TemuEvents temuEvents)
    {
        return temuEventsMapper.updateTemuEvents(temuEvents);
    }

    /**
     * 批量删除TemuEvents
     * 
     * @param ids 需要删除的TemuEvents主键
     * @return 结果
     */
    @Override
    public int deleteTemuEventsByIds(Integer[] ids)
    {
        return temuEventsMapper.deleteTemuEventsByIds(ids);
    }

    /**
     * 删除TemuEvents信息
     * 
     * @param id TemuEvents主键
     * @return 结果
     */
    @Override
    public int deleteTemuEventsById(Integer id)
    {
        return temuEventsMapper.deleteTemuEventsById(id);
    }

    @Override
    public int insTemuEvents(String cookie,String mallid) throws IOException {
        //获取店铺信息
        String dpresp = Httpapi.post(TemuApi.dpinfo, cookie, TemuApi.dpbow,mallid);
        JSONObject jsonObject = JSONUtil.parseObj(dpresp);
        String mallList = jsonObject.getStr("result");
        JSONArray mallList1 = JSONUtil.parseObj(mallList).getJSONArray("mallList");
        String mallId = JSONUtil.parseObj(mallList1.get(0)).getStr("mallId");
        String mallName = JSONUtil.parseObj(mallList1.get(0)).getStr("mallName");

        TemuStore temuStore = temuStoreMapper.selectTemuStoreByStoreId(mallid);
        if (temuStore==null)
        {
            TemuStore temustore=new TemuStore();
            temustore.setStoreId(mallid);
            temustore.setStoreName(mallName);
            temuStoreMapper.insertTemuStore(temustore);
        }
        temuEventsMapper.deledate(DateUtil.today());
        temuSalesDataMapper.deledate(DateUtil.today());

//        //活动信息
        getevents(cookie, mallid);
        //销售数据
        getsales(cookie, mallid);
        return 0;
    }
    private void getsales(String cookie, String mallid) throws IOException {
        //活动
        int pages=999;
        int page=1;
        while (page<=pages)
        {
           String bow= TemuApi.salesbowhead + page++ + TemuApi.salesbowend;
            String resp = Httpapi.post(TemuApi.salesurl, cookie, bow, mallid);
            JSONObject entries = JSONUtil.parseObj(resp);
            int total = JSONUtil.parseObj(entries.getStr("result")).getInt("total");
            if (total==0)
                break;
            if (pages==999)
                pages = (total+40-1)/40;
            JSONArray goods = JSONUtil.parseObj(entries.getStr("result")).getJSONArray("subOrderList");
            List<TemuSalesData> list=new ArrayList<>();
            for (Object good : goods) {
                JSONObject item = JSONUtil.parseObj(good);
                String productName = item.getStr("productName");
                String skcId = item.getStr("productSkcId");
                String spuid = item.getStr("productId");
                String imgurl = item.getStr("productSkcPicture");
                //上升趋势标签
                JSONArray onSalesDurationOffline = item.getJSONArray("skcLabels");
                //商品其他标签
                JSONArray purchaseLabelList = item.getJSONArray("purchaseLabelList");
                JSONArray labs = new JSONArray();
                if (onSalesDurationOffline != null) labs.addAll(onSalesDurationOffline);
                if (purchaseLabelList != null) labs.addAll(purchaseLabelList);
                //上架天数
                Integer sjts = item.getInt("onSalesDurationOffline");
                //评论数
                Integer commentNum = item.getInt("commentNum");
                //商品评分
                Long mark = item.getLong("mark");
                //-----------------------明细数据
                //sku维度数据
                JSONArray skudata = item.getJSONArray("skuQuantityDetailList");
                for (Object skudatum : skudata) {
                    //封装头
                    TemuSalesData temp=new TemuSalesData();
                    temp.setGoodTitle(productName);
                    temp.setSpuId(spuid);
                    temp.setSkcId(skcId);
                    temp.setSalesDays(sjts);
                    temp.setLabel(String.valueOf(labs));
                    temp.setNumberEvaluations(commentNum);
                    temp.setScore(mark);
                    //明细数据处理
                    JSONObject sku = JSONUtil.parseObj(skudatum);
                    String skuid = sku.getStr("productSkuId");
                    //sku信息
                    String className = sku.getStr("className");
                    //sku货号
                    String skuhh = sku.getStr("skuExtCode");
                    //申报价
                    Integer supplierPrice = sku.getInt("supplierPrice");
                    //缺货数
                    Integer lackQuantity = sku.getInt("lackQuantity");
                    Integer inCartNumber7d = sku.getInt("inCartNumber7d");
                    //累计加购数量
                    Integer inCardNumber = sku.getInt("inCardNumber");
                    //今日销量
                    Integer todaySaleVolume = sku.getInt("todaySaleVolume");
                    //七日销量
                    Integer lastSevenDaysSaleVolume = sku.getInt("lastSevenDaysSaleVolume");
                    //30日销量
                    Integer lastThirtyDaysSaleVolume = sku.getInt("lastThirtyDaysSaleVolume");
                    //仓内可用库存
                    Integer salesInventoryNum = sku.getInt("salesInventoryNum");
                    //建议备货数量
                    Integer predictSaleAdviceQuantity = sku.getInt("predictSaleAdviceQuantity");
                    //库存可售天数
                    Long predictSaleAvailableDays = sku.getLong("predictSaleAvailableDays");

                    //备货逻辑
                    String purchaseConfig = sku.getStr("purchaseConfig");

                    //----------------------
                    JSONObject inventoryNumInfo = JSONUtil.parseObj(sku.getStr("inventoryNumInfo"));
                    //仓内预占用库存
                    Integer normalLockNumber = inventoryNumInfo.getInt("normalLockNumber");
                    //仓内不可用库存
                    Integer waitOnShelfNum = inventoryNumInfo.getInt("waitOnShelfNum");
                    //已发货库存
                    Integer waitReceiveNum = inventoryNumInfo.getInt("waitReceiveNum");
                    //已创建备货单代发库存
                    Integer waitDeliveryInventoryNum = inventoryNumInfo.getInt("waitDeliveryInventoryNum");
                    //明细数据填写
                    temp.setImgurl(imgurl);
                    temp.setSkuId(skuid);
                    temp.setSkuItemNumber(skuhh);
                    temp.setOutStockQuantity(lackQuantity);
                    temp.setPurchase7days(inCartNumber7d);
                    temp.setAccumulatedPurchases(inCardNumber);
                    temp.setTodaySalesVolume(todaySaleVolume);
                    temp.setSales7days(lastSevenDaysSaleVolume);
                    temp.setSales30days(lastThirtyDaysSaleVolume);
                    temp.setAvailableStock(salesInventoryNum);
                    temp.setUnavailableInventory(waitOnShelfNum);
                    temp.setIssuedInventory(waitReceiveNum);
                    temp.setPendingInventory(waitDeliveryInventoryNum);
                    temp.setStockingLogic(purchaseConfig);
                    temp.setSuggestedStockingQuantity(predictSaleAdviceQuantity);
                    temp.setAvailableSaleDay(predictSaleAvailableDays);
                    temp.setOccupationInventory(normalLockNumber);
                    temp.setSupplierPrice(supplierPrice);
                    temp.setSkuInfo(className);
                    temp.setDate(DateUtil.date());
                    temp.setStoreId(mallid);
                    list.add(temp);
                }
            }
            temuSalesDataMapper.insdatas(list);
        }
    }
    private void getevents(String cookie, String mallid) {
        //活动
        int pages=999;
        int page=1;
        List<TemuEvents> list=new ArrayList<>();
        while (page<=pages)
        {
            String resp = Httpapi.post(TemuApi.dpEvents, cookie, TemuApi.dpEventsbowhead + page++ + TemuApi.dpEventsbowend, mallid);

            JSONObject entries = JSONUtil.parseObj(resp);
            int total = JSONUtil.parseObj(entries.getStr("result")).getInt("total");
            if (total==0)
                break;
            if (pages==999)
                pages = (total+40-1)/40;
            //所有 活动
            JSONArray huodongs = JSONUtil.parseObj(entries.getStr("result")).getJSONArray("list");
            //处理每个活动
            for (Object huodong : huodongs) {
                JSONObject item = JSONUtil.parseObj(huodong);
                String productId = item.getStr("productId");
                String pictureUrl = item.getStr("pictureUrl");
                String activityTypeName = item.getStr("activityTypeName");
                String enrollTime = item.getStr("enrollTime");
                //活动提报库存
                Integer activityStock = item.getInt("activityStock");
                //剩余库存
                Integer remainingActivityStock = item.getInt("remainingActivityStock");

                //所有活动
                JSONArray assignSessionList = item.getJSONArray("assignSessionList");
                if (assignSessionList==null)
                {
                    System.out.println(productId+":活动为空");
                    continue;
                }
                //进行中的站点
                int sessionStatus = assignSessionList.stream().filter(d -> {
                    return JSONUtil.parseObj(d).getInt("sessionStatus") == 2;
                }).collect(Collectors.toList()).size();
                //暂未开始的站点
                //进行中的站点
                int zwksStatus = assignSessionList.stream().filter(d -> {
                    return JSONUtil.parseObj(d).getInt("sessionStatus") == 1;
                }).collect(Collectors.toList()).size();
                //最后活动结束日期
//                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
//                String maxDate = assignSessionList.stream()
//                        .map(obj -> ((JSONObject)obj).getStr("endDateStr"))
//                        .max(Comparator.comparing(date -> LocalDate.parse(date, formatter)))
//                        .orElse(null);
//                System.out.println(maxDate);
                //skc维度
                JSONArray skcList = item.getJSONArray("skcList");
                JSONArray skuList = JSONUtil.parseObj(skcList.get(0)).getJSONArray("skuList");
                //最低价“activityPrice”
//                int zdactivityPrice = skcList.stream().mapToInt(d -> JSONUtil.parseObj(d).getInt("activityPrice")).min().orElse(-1);
                //填充
                TemuEvents temuEvents = new TemuEvents();
                temuEvents.setPictureUrl(pictureUrl);
                temuEvents.setSpuId(productId);
                temuEvents.setSkcNum(skuList.size());
                temuEvents.setActivityType(activityTypeName);
                temuEvents.setNumberSites(sessionStatus);
                temuEvents.setUnstartedSites(zwksStatus);
                temuEvents.setActivityInventory(activityStock);
                temuEvents.setRemaining(remainingActivityStock);
                temuEvents.setDate(DateUtil.date());
                temuEvents.setRegistrationTime(new java.util.Date(Long.parseLong(enrollTime)));
                temuEvents.setStoreId(mallid);
                list.add(temuEvents);
            }
        }
        temuEventsMapper.bathinsEvents(list);
    }
}
